<script setup lang="ts">
import { ContentWrapNoHeaderLine } from '@/components/ContentWrap'
import {
  ElButton, ElMessage
} from 'element-plus'
import { reactive, ref, unref } from 'vue'
import { ResetpasswordData } from "@/api/config/types";
import { resetPassword } from "@/api/config/index";
import Resetedit from "./resetedit.vue";
import { FormSchema } from "@/types/form";
import { useValidator } from "@/hooks/web/useValidator";

const { required, isEqual } = useValidator()

const loading = ref(false)
const editRef = ref<ComponentRef<typeof Resetedit>>();
const getFormData = async () => {
  const editor = unref(editRef)
  const data = (await editor?.getFormData()) as ResetpasswordData;
  return data;
}
const save = async () => {
  const editor = unref(editRef)
  await editor?.elFormRef?.validate(async (isValid) => {
    if (isValid) {
      loading.value = true
      const data = (await editor?.getFormData()) as ResetpasswordData
      console.log(data)
      const res = await resetPassword(data)
        .catch(() => {
        })
        .finally(() => {
          loading.value = false
        })
      if (res) {
        ElMessage.success(res.msg);
      }
    }
  })
}

const validateEqualPassword = async (rule, value, callback) => {
  console.log(rule)
  console.log(value)
  const formData: ResetpasswordData = await getFormData();
  if (formData.password && formData.again) {
    isEqual(formData.password, formData.again, callback, "两次输入的新密码不一致！");
  }
}
const formSchema = reactive<FormSchema[]>([
  {
    field: 'old',
    label: '旧密码',
    component: 'Input',
    componentProps: {
      type: 'password',
      showPassword: true
    },
    formItemProps: {
      rules: [required()]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'password',
    label: '新密码',
    component: 'Input',
    componentProps: {
      type: 'password',
      showPassword: true
    },
    formItemProps: {
      rules: [required(), { validator: validateEqualPassword }]
    }, colProps: {
      span: 24
    }
  },
  {
    field: 'again',
    label: '重复新密码',
    component: 'Input',
    componentProps: {
      type: 'password',
      showPassword: true
    },
    formItemProps: {
      rules: [required(), { validator: validateEqualPassword }]
    }, colProps: {
      span: 24
    }
  }
]);
const handleReset = () => {
  const edit = unref(editRef)
  edit?.elFormRef?.resetFields()
}

</script>

<template>
  <ContentWrapNoHeaderLine title="管理设置">
    <Resetedit ref="editRef" :form-schema="formSchema" />

    <ElButton type="primary" :loading="loading" @click="save">
      提交
    </ElButton>
    <ElButton @click="handleReset">重置</ElButton>
  </ContentWrapNoHeaderLine>
</template>
